<?php
namespace app\appclass\model;
use app\BaseModel;
use app\card\model\Company;
use think\facade\Db;



class ClassDate extends BaseModel
{
    //定义表名
    protected $name = 'longbing_card_appclass_class_date';



    protected $append = [


        'store_name',

        'coach_info'

    ];


    /**
     * @author chenniang
     * @DataTime: 2021-05-14 14:59
     * @功能说明:门店名字
     */
    public function getStoreNameAttr($value,$data){

        if(!empty($data['store_id'])){

            $company_model = new Company();

            $info = $company_model->where(['id'=>$data['store_id']])->value('name');

            return $info;

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-14 15:00
     * @功能说明:教师信息
     */
    public function getCoachInfoAttr($value,$data){

        if(!empty($data['coach_id'])){

            $info['name'] = lbUserName($data['coach_id']);

            $info['avatar'] = lbUserAvatar($data['coach_id']);

            return $info;

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:00
     * @功能说明:添加
     */
    public function dataAdd($data){

        $res = $this->insert($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-12 09:47
     * @功能说明:后台添加
     */
    public function adminDataAdd($data){

        $update = $data;

        if(!empty($data['coach'])){

            unset($data['coach']);
        }

        if(!empty($data['lable'])){

            unset($data['lable']);
        }

        if(!empty($data['card'])){

            unset($data['card']);
        }

        $res = $this->dataAdd($data);

        $id  = $this->getLastInsID();

        $res = $this->updateSome($id,$update);

        return $res;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-12 09:54
     * @功能说明:
     */
    public function updateSome($id,$data){

        $coach_model = new ClassCoach();

        $lable_model = new ClassLable();

        $card_model  = new ClassCard();

        $event_model = new \app\appclass\server\CardList();
        //绑定名片
        $event_model->addObserver($card_model);
        //绑定标签
        $event_model->addObserver($lable_model);
        //绑定教练
        $event_model->addObserver($coach_model);

        $event_model->notify($data,$id);

        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-12 10:50
     * @功能说明:后台编辑
     */
    public function adminDataUpdate($dis,$data){

        $update = $data;

        if(!empty($data['coach'])){

            unset($data['coach']);
        }

        if(!empty($data['lable'])){

            unset($data['lable']);
        }

        if(!empty($data['card'])){

            unset($data['card']);
        }

        $res = $this->dataUpdate($dis,$data);

        $res = $this->updateSome($dis['id'],$update);

        return $res;

    }





    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:03
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){

        $res = $this->where($dis)->update($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:04
     * @功能说明:详情
     */
    public function dataInfo($dis,$file='*'){

        $data = $this->where($dis)->field($file)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-18 10:45
     * @功能说明:列表
     */
    public function indexDataListV2($dis,$page=10){

        $data = $this->where($dis)->group('start_time desc,id desc')->paginate($page)->toArray();

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['start_time'] = date('Y-m-d H:i',$v['start_time']).'-'.date('H:i',$v['end_time']);

            }

        }

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:05
     * @功能说明:
     */
    public function dataList($dis){

        $data = $this->alias('a')
                ->join('longbing_card_appclass_class_list b','a.class_id = b.id','left')
                ->where($dis)
                ->group('a.id')
                ->field('a.*,a.title as class_title')
                ->order('a.start_time')
                ->select()
                ->toArray();

        if(!empty($data)){

            foreach ($data as &$v){

                $v['coach_name'] = lbUserName($v['coach_id']);

                $v['day_time']   = date('H:i',$v['start_time']).'-'.date('H:i',$v['end_time']);

            }

        }

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-19 09:27
     * @功能说明:获取每一周的开始时间
     */
    public function getStartTimeGroup($dis){

        $data = $this->alias('a')
            ->join('longbing_card_appclass_class_list b','a.class_id = b.id','left')
            ->where($dis)
            ->group('a.hour')
            ->order('a.hour')
            ->column('a.hour');

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-11 16:05
     * @功能说明:前端列表
     */
    public function indexDataList($dis,$page=10){

        $data = $this->alias('a')
            ->join('longbing_card_appclass_class_list b','a.class_id = b.id','left')
            ->where($dis)
            ->group('a.id')
            ->field('a.*,a.title as class_title')
            ->order('a.start_time')
            ->paginate($page)
            ->toArray();

        if(!empty($data['data'])){

            $lable_model = new ClassLable();

            foreach ($data['data'] as &$v){

                $v['coach_name']   = lbUserName($v['coach_id']);

                $v['coach_avatar'] = lbUserAvatar($v['coach_id']);

                $v['start_time_text'] = date('H:i',$v['start_time']);

                $v['end_time_text']   = date('H:i',$v['end_time']);
                //剩余报名人数
                $v['over_num'] = $v['num']- $v['have_num'];
                //标签
                $v['lable'] = $lable_model->classLable($v['class_id']);

            }

        }

        return $data;

    }

    /**
     * @author chenniang
     * @DataTime: 2021-05-12 16:34
     * @功能说明:添加排课
     */
    public function classDataAdd($data){

        Db::startTrans();

        foreach ($data['date'] as $v){

            $res = $this->classDataSave($data,$v['start_time'],$v['end_time']);

            if(!empty($res['code'])){

                Db::rollback();
            }

        }

        Db::commit();

        return $res;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-12 17:27
     * @功能说明:编辑排课
     */
    public function classDataSave($data,$start_time,$end_time){

        $id = !empty($data['id'])?$data['id']:0;
        //检查教练时间
        $res = $this->checkCoach($data['coach_id'],$start_time,$end_time,$id);

        if($res==false){

            return ['code'=>500,'msg'=>'该教练该时间段已有课程!'];
        }

       if(!empty($id)){

           $info = $this->dataInfo(['id'=>$id]);

           if($data['num']<$info['have_num']){

               return ['code'=>500,'msg'=>'该课程已经预约'.$info['have_num'].'人,容纳人数不得小于'.$info['have_num']];

           }

       }


        //检查教室
        $res = $this->checkRoom($data['room_id'],$data['num'],$start_time,$end_time,$id);

        if(!empty($res['code'])){

            return $res;
        }

        if(isset($data['date'])){

            unset($data['date']);
        }

        $data['start_time'] = $start_time;

        $data['end_time']   = $end_time;

        $data['hour']   = date('H:s',$start_time);
        //取消时间
        $data['auto_cancel_time'] = $data['start_time']-$data['cancel_time']*60;

        if(!empty($id)){

            $res = $this->dataUpdate(['id'=>$id],$data);
            //同步已经预约的
            $this->initRecord($data);

        }else{

            $data['create_time'] = time();

            $data['update_time'] = time();

            $data['status']  = 1;

            $res = $this->insert($data);
        }

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-20 15:15
     * @功能说明:初始化记录
     */
    public function initRecord($data){

        $update = [

            'class_id'   => $data['class_id'],

            'store_id'   => $data['store_id'],

            'coach_id'   => $data['coach_id'],

            'class_date_id'=> $data['id'],

            'cate_id'    => $data['cate_id'],

            'room_id'    => $data['room_id'],

            'time_long'  => $data['time_long'],

            'start_time' => $data['start_time'],

            'end_time'   => $data['end_time'],

            'title'      => $data['title'],

            'difficulty' => $data['difficulty'],
        ];

        $record_model = new ClassRecord();

        $res = $record_model->dataUpdate(['class_date_id'=>$data['id']],$update);

        return $res;


    }

    /**
     * @author chenniang
     * @DataTime: 2021-05-12 16:35
     * @功能说明:检查教练排课时间
     */
    public function checkCoach($id,$start_time,$end_time,$class_id=0){

        $dis = [

            'coach_id' => $id
        ];

        $list = $this->where($dis)->where('end_time','>',$start_time)->where('status','>',-1)->where('id','<>',$class_id)->select()->toArray();

        if(!empty($list)){

            foreach ($list as $value){
                //判断时间段是否有交集
                $res = is_time_cross($value['start_time'],$value['end_time'],$start_time,$end_time);

                if($res==false){

                    return $res;
                }

            }
        }


        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-12 16:48
     * @功能说明:检查教室
     */
    public function checkRoom($room_id,$num,$start_time,$end_time,$class_id=0){

        $room_model = new ClassRoom();

        $room = $room_model->dataInfo(['id'=>$room_id]);

        if($room['num']<$num){

            return ['code'=>500,'msg'=>'超出教室人数限制'];

        }

        $dis = [

            'room_id' => $room_id
        ];

        $list = $this->where($dis)->where('end_time','>',$start_time)->where('status','>',-1)->where('id','<>',$class_id)->select()->toArray();

        if(!empty($list)){

            foreach ($list as $value){
                //判断时间段是否有交集
                $res = is_time_cross($value['start_time'],$value['end_time'],$start_time,$end_time);

                if($res==false){

                     return ['code'=>500,'msg'=>'该教室该时间段已有课程'];
                }

            }
        }

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-20 14:33
     * @功能说明:排课次数
     */
    public function classDateCount($dis,$where=[]){

//        $dis['status'] = 1;

        $count = $this->where($dis)->where($where)->where('status','>',-1)->count();

        return $count;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-20 14:41
     * @功能说明:教师数量
     */
    public function coachCount($dis,$where1 = []){

        $count = $this->where($dis)->where($where1)->where('status','>',-1)->column('coach_id');
        //私教课数量
        $record_model = new ClassRecord();

        $private = $record_model->where($dis)->where($where1)->where('status','in',[1,3])->column('coach_id');

        $data =array_unique(array_merge($count,$private));

        return count($data);

    }







    /**
     * @author chenniang
     * @DataTime: 2021-05-31 16:01
     * @功能说明:教师排课列表(未开始)
     */
    public function coachClassRecord($where,$page=10){

        $record_model = new ClassRecord();

        $a = $record_model->where('status','in',[1,3])->where(['class_type'=>1])->where($where)->count();

        $b = $this->where($where)->where('status','in',[1,2])->count();

        $all_count = $a+$b;

        $a = $record_model->field(['id','num as have_num','title','start_time','end_time','cate_id'])->where('status','in',[1,3])->where(['class_type'=>1])->where($where)->order('start_time desc,id desc')->buildSql();

        $data = $this->where($where)->field(['id','have_num','title','start_time','end_time','cate_id'])->where('status','in',[1,2])->unionAll([$a])->order('start_time desc,id desc')->paginate(10,$all_count)->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-15 14:27
     * @功能说明:删除排课
     */
    public function delClassDate($id){

        $record_model = new ClassRecord();

        $dis = [

            'class_date_id' => $id
        ];

        $record = $record_model->where($dis)->where('status','in',[1,3])->find();

        if(!empty($record)){

            $this->errorMsg('该排课已被预约，无法删除');
        }

        $res = $this->dataUpdate(['id'=>$id],['status'=>-1]);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-22 13:35
     * @功能说明:取消预约失败的排课|课程成功后修改排课的状态|课程结束后修改没有前端的状态
     *
     *
     */
    public function cancelfailClass($uniacid,$cancel_user = -1){

        $dis[] = ['uniacid','=',$uniacid];

        $dis[] = ['start_limit','=',1];

        $dis[] = ['auto_cancel_time','<',time()];

        $dis[] = ['status','=',1];

        $list = $this->where($dis)->whereColumn('app_num','>','have_num')->field('id,auto_cancel_time')->select()->toArray();

        $record_model = new ClassRecord();

        if(!empty($list)){

            foreach ($list as $v){

                Db::startTrans();

                $where[] = ['status','in',[1,3]];

                $where[] = ['class_date_id','=',$v['id']];

                $record = $record_model->where($where)->select()->toArray();

                if(!empty($record)){

                    foreach ($record as $value){

                        $res = $record_model->recordCancel($value['id'],$cancel_user,0,$v['auto_cancel_time']);

                        if($res != true){

                            Db::rollback();

                        }

                    }

                }
                //取消约课
                $res = $this->where(['id'=>$v['id']])->whereColumn('app_num','>','have_num')->update(['status'=>3,'auto_cancel'=>1]);

                if($res != true){

                    Db::rollback();

                }

                Db::commit();

            }

        }
        //改变课程成功的状态
        $dis = [

            'uniacid' => $uniacid,

            'status'  => 1
        ];

        $this->where($dis)->where('end_time','<',time())->update(['status'=>2]);
        //课程结束后给没有签到的签到
        $record_model->where($dis)->where('end_time','<',time())->update(['status'=>3,'auto_sign'=>1]);

        return true;

    }



}